package practise.remoteapitest;

import static com.googlecode.objectify.ObjectifyService.ofy;
import gwtappcontainer.server.apps.home.main.AllAppURLEntity;
import gwtappcontainer.server.apps.home.main.FlashNewsEntity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.Query;
import com.googlecode.objectify.cmd.QueryKeys;

public class RemoteApiExample {

	/**
	 * @param args
	 */
	
	static {
		ObjectifyService.factory().register(EntityWithEmbedded.class);
		ObjectifyService.factory().register(Member.class);
		ObjectifyService.factory().register(Event.class);
		ObjectifyService.factory().register(Attendance.class);
		ObjectifyService.factory().register(Center.class);
		ObjectifyService.factory().register(FlashNewsEntity.class);
		ObjectifyService.factory().register(App.class);
		ObjectifyService.factory().register(AllAppURLEntity.class);				
	}
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub		
		
		RemoteApiOptions options = new RemoteApiOptions()
			.server("ishaportal.appspot.com", 443)
			.credentials("sathyanarayanant", "gu1tarlady");
		
//		RemoteApiOptions options = new RemoteApiOptions()
//			//.server("http://localhost:8888/", 443)
//			.server("localhost", 8888)
//			.credentials("dummy", "dummy");
		
		RemoteApiInstaller installer = new RemoteApiInstaller();
		installer.install(options);
		
		try {
			//testEntityWithEmbedded();
			//populateMembers();
			//makeNameLowerCase();
			//queryMembers();
//			populateMembers();
//			populateAttendance();
//			populateEvents();
			//loadAllMembers();
			//deleteAllMembers();
			//populateCenters();
			//create10000Members();
			//populateMembers();
			//disableFlashNewsEntity();
			//addApp("Registration Status");
			//displayApps();
			setAllAppHtml();
			
		} finally {
			installer.uninstall();
		}
	}
	
	private static void setAllAppHtml() {
		final String app = "Home";
		
		NamespaceManager.set(app);
		
		AllAppURLEntity e = new AllAppURLEntity();
		e.allIconsAndURLsHtml = 
				"<style type=\"text/css\">" +
						   "img { padding-left: 15px; padding-right: 15px; padding-top: 15px; padding-bottom: 15px;}" +
						"</style>" + 

						"<a href=\"https://drive.google.com/?authuser=0#folders/0B6X4onKwzUaLNVJuSklZYUIzdG8\" target=\"_blank\"><img src=\"http://i.imgur.com/P7dp1A1.jpg\"  width=\"75\">" + 									
						"<a href=\"http://ishaportal.appspot.com/#videos/view\"><img src=\"http://i.imgur.com/bREMZIt.jpg\"  width=\"65\">";
		
		List<AllAppURLEntity> all = ofy().load().type(AllAppURLEntity.class).list();
		
		if (0 != all.size()) {
			System.out.println("deleting existing entities...");
			ofy().delete().entities(all).now();
		}
		
		System.out.println("saving new entity...");
		ofy().save().entity(e).now();
		
		System.out.println("saved.");
	}
	
	private static void addApp(String name) {
		App app = new App();
		app.name = name;
				
		NamespaceManager.set(App.namespace);
		System.out.println("adding app [" + name + "] in namespace [" + NamespaceManager.get() + "]");
		ofy().save().entity(app).now();							
	}
	
	private static void displayApps() {
		NamespaceManager.set(App.namespace);
		
		System.out.println("reatrieving all App entities. current namespace = " + NamespaceManager.get());

		List<App> apps = ofy().load().type(App.class).list();
		
		System.out.println("no of apps = " + apps.size());
		
		for (App app2 : apps) {
			System.out.println(app2);
		}
	}
	
	private static void disableFlashNewsEntity() {
		List<FlashNewsEntity> all = ofy().load().type(FlashNewsEntity.class).list();
		
		FlashNewsEntity fne = all.get(0);
		System.out.println("current value of show: " + fne.show);
		
		System.out.println("setting show to false");
		fne.show = false;
		
		ofy().save().entity(fne).now();
		
		System.out.println("loading again...");
		all = ofy().load().type(FlashNewsEntity.class).list();
		System.out.println("value of show = " + all.get(0).show);
		

		
	}
	
	private static void populateCenters() {
		ArrayList<Center> centers = new ArrayList<Center>();
		
		centers.add(new Center("Singapore"));
		centers.add(new Center("Malaysia/KL"));
		centers.add(new Center("Malaysia/Penang"));
		centers.add(new Center("Australia/Melbourne"));
		centers.add(new Center("Australia/Sydney"));
		
		System.out.println(new Date() + " - saving centers into datastore");
		ofy().save().entities(centers);
		System.out.println(new Date() + " - completed");
	}
	
	private static void testEntityWithEmbedded() {
		EntityWithEmbedded e = new EntityWithEmbedded();
		e.one.foo = "sathya";
		e.one.two.bar = "sowmya";
		
		ofy().save().entity(e).now();
		System.out.println("key of new entity is: " + e.id);
	}
	
	private static void populateMembers() {
		
		System.out.println(new Date() + " - loading center for ids 1, 2");		
		Map<Long, Center> centers = ofy().load().type(Center.class).ids(1L, 2L);
		System.out.println(new Date() + " - loaded centers");
		
		Center sgp = centers.get(1L);
		Center kl = centers.get(2L);
		
		ArrayList<Member> members = new ArrayList<Member>();
		
		//singapore				
		for (int i = 0; i < 500; i++) {
			Member member = new Member();
			member.nameFirst = "sathyanarayanan";
			member.nameLast = "thilakan";
			
			member.email1 = "sathya.t@ishafoundation.org";
			
			member.phoneHome = new Phone("65", "", "65227030");
			member.phoneOffice = new Phone("65", "", "63083013");
			member.phoneMobile = new Phone("65", "", "98361844");
			
			member.addressHome = "Block 292B, 09-210, Compassvale Street, Singapore 542292";
			member.addressOffice = "Level 28, South Tower, One Raffles Quay, Singapore 048583";
						
			member.addCenter(sgp);
			members.add(member);
		}
		
		//kl				
		for (int i = 0; i < 500; i++) {
			Member member = new Member();
			member.nameFirst = "weibeng";
			member.nameLast = "ong";
			
			member.email1 = "ongweibeng@hotmail.com";
						
			member.phoneMobile = new Phone("60", "", "123516310");
			
			member.addressHome = "kl street, kl, malaysia";			
						
			member.addCenter(kl);
			members.add(member);
		}
				
		//tina belongs to both singapore and kl
		Member member = new Member();
		member.nameFirst = "marie christine";
		member.nameLast = "jabr";		
		member.email1 = "tina@ishafoundation.org";
		member.email2 = "tina.jabr@gmail.com";
		member.addCenter(sgp);
		member.addCenter(kl);
		members.add(member);
										
		System.out.println(new Date() + " - saving " + members.size() + " entities in datastore.");
		ofy().save().entities(members).now();
		System.out.println(new Date() + " - saved");								
	}
	
	public static void makeNameLowerCase() {
		System.out.println(new Date() + " - loading all members");
		List<Member> all = ofy().load().type(Member.class).list();
		
		System.out.println(new Date() + " - making names in lower case for all loaded members");
		for (Member member : all) {
			member.nameFirst = member.nameFirst.toLowerCase();
			member.nameLast = member.nameLast.toLowerCase();
			member.nameMiddle = member.nameMiddle.toLowerCase();
		}
		
		System.out.println(new Date() + " - saving members back to datastore");
		ofy().save().entities(all).now();
		System.out.println(new Date() + " - saving complete");
	}

	private static void queryMembers() {
		
		System.out.println(new Date() + " - loading center for ids 1, 2");		
		Map<Long, Center> centers = ofy().load().type(Center.class).ids(1L, 2L);
		System.out.println(new Date() + " - loaded centers");
		
		Center sgp = centers.get(1L);
		Center kl = centers.get(2L);
		
		
		
		//search by first name or last name or phone or email
		Center searchCenter = sgp;
		String searchString = "sath";
		searchString = searchString.toLowerCase();
		
		System.out.println(new Date() + " - quering for Center + " + searchCenter +  
		" searchString [" + searchString + "]");
		
		Iterable<Member> members = ofy().load().type(Member.class).filter("centers", sgp)
				.filter("nameFirst >=", searchString)
				.filter("nameFirst <", searchString + "\uFFFD");
		
		System.out.println(new Date() + " - listing query results");
		System.out.println("--------------------------------");
		for (Member m : members) {
			System.out.println(m);			
		}
		System.out.println("--------------------------------");
		
	}
	
	private static void populateEvents() {
		Event e1 = new Event("sathsang jan 2013", "singapore");
		Event e2 = new Event("sathsang feb 2013", "singapore");
		Event e3 = new Event("sathsang mar 2013", "singapore");
		Event e4 = new Event("sathsang jan 2013", "malaysia");
		Event e5 = new Event("sathsang feb 2013", "malaysia");
		
		ofy().save().entities(e1, e2, e3, e4, e5);
	}
	
	private static void populateAttendance() {
				
		Event event = ofy().load().type(Event.class).id(3).get();
		
		System.out.println("event id  " + event.id);
		Key<Event> eventKey = Key.create(Event.class, 3);
		
		Query<Member> allMembers = ofy().load().type(Member.class);
		System.out.println("no of members = " + allMembers.count());
		
		
		ArrayList<Attendance> attendances = new ArrayList<Attendance>();
		for (Member member : allMembers) {
			Attendance attendance = new Attendance();
			attendance.memberKey = Key.create(Member.class, member.id);
			attendance.eventKey = eventKey;		
			attendances.add(attendance);
		}								
		
		ofy().save().entities(attendances);
	}
	
	private static void loadAllMembers() {
		System.out.println(new Date() + " - loading all members");
		long startTime = System.currentTimeMillis();
		QueryKeys<Member> allKeys = ofy().load().type(Member.class).keys();
		System.out.println(new Date() + " - loaded all keys");
		
		Map<Key<Member>, Member> all = ofy().load().keys(allKeys);
				
//		for (Member member : all) {
//			member.name = member.name;
//		}
				
		long endTime = System.currentTimeMillis();
		System.out.println(new Date() + " - loaded " + all.size() + " members in "
				+ (endTime - startTime) + " milliseconds");				
	}
	
	private static void deleteAllMembers() {
		System.out.println(new Date() + " - loading all keys");
				
		QueryKeys<Member> allKeys = ofy().load().type(Member.class).keys();
		System.out.println(new Date() + " - loaded " + allKeys.list().size() +  " keys, deleting all of them");		
		ofy().delete().keys(allKeys);					
		System.out.println(new Date() + " - all members deleted");
	}
	
	
	private static void listAttendance() {
		Query<Attendance> all = ofy().load().type(Attendance.class);
		
		
	}		
}


